package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @PackageName: com.itheima.common
 * @ClassName: GlobalExceptionHandler
 * @Description:
 * @Author: zhangcheng
 * @DateTime: 2022/6/6 19:01
 * @Version 1.0
 */

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    /**
     * 新增账号已存在问题
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerSQLConstraintException(SQLIntegrityConstraintViolationException ex) {
        //打印异常信息
        String errMsg = ex.getMessage();//Duplicate entry '111' for key 'employee'
        log.error(errMsg);
        if (errMsg.contains("Duplicate entry")) {
            String[] split = errMsg.split("'");
            String msg = split[1] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
}
